import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like } from 'typeorm';
import { Topic } from './entities/topic.entity';
import { CreateTopicDto } from './dto/create-topic.dto';
import { WxUserService } from '../wxuser/wxuser.service';
import { FavoriteService } from '../favorite/favorite.service';

@Injectable()
export class TopicService {
  constructor(
    @InjectRepository(Topic)
    private readonly topicRepository: Repository<Topic>,
    private readonly wxUserService: WxUserService,
    private readonly favoriteService: FavoriteService,
  ) {}

  async create(createTopicDto: CreateTopicDto) {
    const topic = this.topicRepository.create(createTopicDto);
    return this.topicRepository.save(topic);
  }

  async findAll() {
    return this.topicRepository.find();
  }
  async remove(id: number) {
    return await this.topicRepository.delete(id);
  }
  async getList(query: any = {}) {
    const { page, size, title = '', userId } = query;
    const searchObj = {
      // 根据关键词模糊查询
      where: {
        title: Like(`%${title}%`),
        ...(userId !== undefined && { userId }), // 如果 userId 存在，则添加到查询条件中
      },
      // 根据分页信息查询
      skip: (page - 1) * size, // 从第x页开始，需要x条数据
      take: size,
    };

    const totalNum = {
      where: {
        title: Like(`%${title}%`),
        ...(userId !== undefined && { userId }), // 如果 userId 存在，则添加到查询条件中
      },
    };

    const data = await this.topicRepository.find(searchObj);
    const total = await this.topicRepository.count(totalNum);
    // 为每个话题添加用户名
    // 为每个话题添加微信用户名
    const dataWithUsername = await Promise.all(
      data.map(async (topic) => {
        const wxUser = await this.wxUserService.getUserById(topic.userId);
        return {
          ...topic,
          username: wxUser?.username || '未知用户',
          avatar: wxUser?.avatar || '',
        };
      }),
    );
    // 从数据库中获取结果，并作为响应返回
    return {
      data: dataWithUsername,
      total,
    };
  }
  async getTopicWithFavoriteStatus(topicId: number, userId: number) {
    const topic = await this.topicRepository.findOne({
      where: { id: topicId },
    });
    if (!topic) {
      throw new NotFoundException('话题不存在');
    }
    // 根据用户 ID 获取用户信息
    const wxUser = await this.wxUserService.getUserById(topic.userId);
    // 检查用户是否收藏该话题
    const isFavorite = await this.favoriteService.isFavorite(userId, topicId);

    // 将布尔值转换为 0 或 1
    // const isLike = isFavorite ? 1 : 0;
    return {
      ...topic,
      isFavorite,
      username: wxUser?.username || '未知用户',
      avatar: wxUser?.avatar || '',
    };
  }

  // 新增方法：通过用户 ID 获取所有话题
  async getUserTopics(userId: number) {
    const topics = await this.topicRepository.find({
      where: { userId },
    });
    console.log('查询到的话题数量:', topics.length); // 打印查询到的话题数量
    console.log('查询到的话题:', topics); // 打印查询到的话题

    // 为每个话题添加微信用户信息
    const topicsWithWxUser = await Promise.all(
      topics.map(async (topic) => {
        const wxUser = await this.wxUserService.getUserById(topic.userId);
        return {
          ...topic,
          wxUser: {
            username: wxUser?.username || '未知用户',
            avatar: wxUser?.avatar || '',
          },
        };
      }),
    );
    return {
      data: topicsWithWxUser,
      total: topicsWithWxUser.length,
    };
  }
}
